package com.test.search;

public class BinarySearch {
    public static void main(String[] args) {
        int arr[] = {1, 8, 10, 89, 100, 1000, 1234};
        int resIndex = search2(arr, 0, arr.length - 1, 1000);//考虑只有单个值的查找
        System.out.println(resIndex);
    }

    public static int search(int arr[], int left, int right, int findVal) {
        if (left > right) return -1;
        int mid = (left + right) / 2;
        if (arr[mid] < findVal) {
            return search(arr, mid + 1, right, findVal);
        } else if (arr[mid] > findVal) {
            return search(arr, left, mid - 1, findVal);
        } else {
            return mid;
        }
    }

    public static int search2(int arr[], int left, int right, int findVal) {
        while (left < right) {
            int mid = (left + right) / 2;
            if (arr[mid] < findVal) {
                left = mid+1;
            } else if (arr[mid] > findVal) {
                right = mid-1;
            } else {
                return mid;
            }
        }
        return -1;
    }
}
